package com.smartmail.view;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ReadMailWebView extends WebView {

	public ReadMailWebView(Context context) {
		super(context);
		this.context = context;
		init();

	}
	public ReadMailWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
	}
	public ReadMailWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		init();
	}
	
	/**
	 * In case, for some tests.
	 */
	private void init(){
	}
	
	/**
	 * Movement of top panel is done here.
	 */
	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt){
		super.onScrollChanged(l, t, oldl, oldt);
		int y = this.getScrollY();
		if (y < layoutTopHeight){
			topContainer.scrollTo(0, y);			
		}
		else {
			topContainer.scrollTo(0, layoutTopHeight10);
		}
	}
    
    public void setTopContainer(FrameLayout t){
    	topContainer = t;
    }
    
    public void setTop(RelativeLayout t){
    	top = t;
    }
    
    public void setDensity(float d){
    	density = d;
    }
    
    /**
     * This method sets all height needed params for placing 
     * components at proper positions.
     * 
     * @param h - height of topPanel from listener
     */
    public void setLayoutTopHeight(int h){  
    	double tempHeight = (double) h;
    	double densityHeight = tempHeight / density;
    	int height = (int) densityHeight;
    	contentSpacer = height;
    	layoutTopHeight = h;
    	layoutTopHeight10 = h + 10;
    	setContent();
    }
    
    /**
     * 
     * @param c - contains text/html which will be loaded in webView.
     */
    public void loadContent(String c){
    	if (c == null) content = "";
    	else {
        	if (c.toLowerCase().contains("<html>") 
        			|| c.toLowerCase().contains("<body>") 
        			|| c.toLowerCase().contains("<head>")) content = c;
        	else content = c.replace("\n", "<br>");
        	
    	}
    }
    
    private void setContent(){
    	
    	String upContent = "<img src=\"\" height=\""+ contentSpacer + "\"><br>" + content;
    	
    	this.loadDataWithBaseURL("", upContent, "text/html", "UTF-8", "");

    }
    
    private String content;
	private int layoutTopHeight;
	private int layoutTopHeight10;
	private int contentSpacer;
	private FrameLayout topContainer;
	private RelativeLayout top;
	private Context context;
	private float density;
	private int allHeight;
}
